<template>
	<view class="container">
		<view class="main" v-if="goods">
			<view class="nav">
				<view class="header">
					<view class="left overflow-hidden">
						<view class="d-flex align-items-center overflow-hidden" v-if="takeType == '外卖配送' && address">
							<image src="/static/images/order/location.png" style="width: 30rpx; height: 30rpx;" class="mr-10"></image>
							<text>{{ address.dorm + '-' + address.detail }}</text>
						</view>
					</view>
					<view class="right">
						<view class="dinein" :class="{ active: takeType != '外卖配送' }" @tap="takein"><text>到店自取</text></view>
						<view class="takeout" :class="{ active: takeType == '外卖配送' }" @tap="takeout"><text>外卖配送</text></view>
					</view>
				</view>
				<view class="coupon">
					<text class="title">可以到店在线点餐也可外卖点餐，赶紧下单吧~</text>
					<view class="iconfont iconarrow-right"></view>
				</view>
			</view>
			<view class="content">
				<!-- 左侧菜单栏 -->
				<scroll-view class="menus" :scroll-into-view="menuScrollIntoView" scroll-with-animation scroll-y>
					<view class="wrapper">
						<view
							v-for="(item, index) in goods"
							class="menu"
							:id="`menu-${item.goodsCategoryName}`"
							:class="{ current: item.goodsCategoryName === currentCategoryName }"
							:key="index"
							@tap="handleMenuTap(item.goodsCategoryName)"
						>
							<text>{{ item.goodsCategoryName }}</text>
							<view class="dot" v-show="menuCartNum(item.goodsCategoryName)">{{ menuCartNum(item.goodsCategoryName) }}</view>
						</view>
					</view>
				</scroll-view>

				<!-- 右侧商品列表 begin -->
				<scroll-view class="goods" scroll-with-animation scroll-y :scroll-top="categoryScrollTop" @scroll="handleGoodsScroll">
					<view class="wrapper">
						<!-- 商品最上方的轮放图 -->
						<swiper class="ads" id="ads" autoplay :interval="3000" indicator-dots>
							<swiper-item v-for="(image, index) in swiperImages" :key="index"><image :src="image"></image></swiper-item>
						</swiper>
						<view class="list">
							<!-- 商品分类展示 begin -->
							<view class="categorygory" v-for="(category, index) in goods" :key="index" :id="`category-${category.goodsCategoryName}`">
								<view v-if="category.goodsList.length">
									<text class="title">{{ category.goodsCategoryName }}</text>
								</view>
								<view class="items">
									<!-- 商品列表 begin -->
									<view class="good" v-for="(goods, key) in category.goodsList" :key="key">
										<image :src="goodsImageBaseUrl + goods.image" class="image" @tap="showGoodDetailModal(goods)"></image>
										<view class="right">
											<text class="name">{{ goods.name }}</text>
											<text class="tips">{{ goods.description }}</text>
											<view class="price_and_action">
												<text class="price">￥{{ goods.defaultPrice / 100 }}</text>
												<view class="btn-group" v-if="goods.goodsPropertyVos && goods.goodsPropertyVos.length">
													<button type="primary" class="btn property_btn" hover-class="none" size="mini" @tap="showGoodDetailModal(goods)">
														选规格
													</button>
													<view class="dot" v-show="goodsCartNum(goods.id)">{{ goodsCartNum(goods.id) }}</view>
												</view>
												<view class="btn-group" v-else>
													<button
														type="default"
														v-show="goodsCartNum(goods.id)"
														plain
														class="btn reduce_btn"
														size="mini"
														hover-class="none"
														@tap="handleReduceFromCart(goods)"
													>
														<view class="iconfont iconsami-select"></view>
													</button>
													<view class="number" v-show="goodsCartNum(goods.id)">{{ goodsCartNum(goods.id) }}</view>
													<button type="primary" class="btn add_btn" size="min" hover-class="none" @tap="handleAddToCart(goods)">
														<view class="iconfont iconadd-select"></view>
													</button>
												</view>
											</view>
										</view>
									</view>
									<!-- 商品 end -->
								</view>
							</view>
							<!-- 商品分类展示 end -->
						</view>
					</view>
				</scroll-view>
				<!-- 右侧商品列表 end -->
			</view>
			<!-- content end -->
			<!-- 购物车栏 begin -->
			<view class="cart-box" v-if="cart && cart.length" @tap="openCartPopup">
				<view class="mark">
					<image src="/static/images/menu/cart.png" class="cart-img"></image>
					<view class="tag">{{ getCartGoodsNumber }}</view>
				</view>
				<view class="price">￥{{ getCartGoodsPrice / 100 }}</view>
				<button type="primary" class="pay-btn" @tap="toPay" :disabled="disabledPay">{{ disabledPay ? `差${spread / 100}元起送` : '去结算' }}</button>
			</view>
			<!-- 购物车栏 end -->
		</view>

		<!-- 商品详情模态框 begin -->
		<modal :show="goodDetailModalVisible" class="good-detail-modal" color="#5A5B5C" width="90%" custom padding="0rpx" radius="12rpx">
			<view class="cover">
				<image v-if="currentGoods.image" :src="goodsImageBaseUrl + currentGoods.image" class="image"></image>
				<view class="btn-group">
					<image src="/static/images/menu/share-goodspng"></image>
					<image src="/static/images/menu/close.png" @tap="closeGoodDetailModal"></image>
				</view>
			</view>
			<scroll-view class="detail" scroll-y style="padding-bottom: 100px;">
				<view class="wrapper">
					<view class="basic">
						<view class="name">{{ currentGoods.name }}</view>
						<view class="tips">{{ currentGoods.description }}</view>
					</view>
					<!-- 商品的额外属性 -->
					<view class="properties" v-if="currentGoods.goodsPropertyVos && currentGoods.goodsPropertyVos.length">
						<view class="property" v-for="(goodsPropertyVo, index) in currentGoods.goodsPropertyVos" :key="index">
							<view class="title">
								<text class="name">{{ goodsPropertyVo.category }}</text>
							</view>
							<view class="values">
								<view
									class="value"
									v-for="(property, index2) in goodsPropertyVo.propertyList"
									:key="index2"
									:class="{ default: property.isDefault }"
									@tap="changePropertyDefault(index, index2)"
								>
									{{ property.propertyOption }}
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="action">
				<!-- 价格和属性 -->
				<view class="left">
					<view class="price">￥{{ currentGoods.realPrice / 100 }}</view>
					<view class="props" v-if="getGoodSelectedProps(currentGoods)">{{ getGoodSelectedProps(currentGoods) }}</view>
				</view>
				<!-- 模态窗里面增减商品 -->
				<view class="btn-group">
					<button type="default" plain class="btn" size="mini" hover-class="none" @tap="changeCurrentGoodsNumber(-1)">
						<view class="iconfont iconsami-select"></view>
					</button>
					<view class="number">{{ currentGoods.number }}</view>
					<button type="primary" class="btn" size="min" hover-class="none" @tap="changeCurrentGoodsNumber(1)"><view class="iconfont iconadd-select"></view></button>
				</view>
			</view>
			<view class="add-to-cart-btn" @tap="addCurrentGoodsToCart()"><view>确认</view></view>
		</modal>
		<!-- 商品详情模态框 end -->

		<!-- 购物车详情popup -->
		<popup-layer direction="top" :show-pop="cartPopupVisible" class="cart-popup">
			<template slot="content">
				<view class="top"><text @tap="handleCartClear">清空</text></view>
				<scroll-view class="cart-list" scroll-y>
					<view class="wrapper">
						<view class="item" v-for="(goods, index) in cart" :key="index">
							<view class="left">
								<view class="name">{{ goods.name }}</view>
								<view class="props">{{ getGoodSelectedProps(goods) }}</view>
							</view>
							<view class="center">
								<text>￥{{ goods.realPrice / 100 }}</text>
							</view>
							<view class="right">
								<!-- 购物车里添加数量 -->
								<button type="default" plain size="mini" class="btn" hover-class="none" @tap="handleCartItemReduce(index)">
									<view class="iconfont iconsami-select"></view>
								</button>
								<view class="number">{{ goods.number }}</view>
								<!-- 购物车里减少数量 -->
								<button type="primary" class="btn" size="min" hover-class="none" @tap="handleCartItemAdd(index)">
									<view class="iconfont iconadd-select"></view>
								</button>
							</view>
						</view>
						<view class="item" v-if="takeType == '外卖配送'">
							<view class="left"><view class="name">包装费</view></view>
							<view class="center">
								<text>￥{{ appProperties.packingPrice / 100 }}</text>
							</view>
							<view class="left"><view class="name">配送费</view></view>
							<view class="center">
								<text>￥{{ appProperties.sendingPrice / 100 }}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</template>
		</popup-layer>
		<!-- 购物车详情popup -->
	</view>
</template>

<script>
import modal from '@/components/modal/modal';
import popupLayer from '@/components/popup-layer/popup-layer';
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';

export default {
	components: {
		modal,
		popupLayer
	},
	data() {
		return {
			goods: [
				{
					displayOrder: 1,
					goodsCategoryName: '新品推荐',
					goodsCategoryShow: true,
					goodsList: []
				},
				{
					displayOrder: 2,
					goodsCategoryName: '招牌热卖',
					goodsCategoryShow: true,
					goodsList: []
				},
				{
					displayOrder: 3,
					goodsCategoryName: '奶茶',
					goodsCategoryShow: true,
					goodsList: []
				},
				{
					displayOrder: 4,
					goodsCategoryName: '果茶',
					goodsCategoryShow: true,
					goodsList: [
						{
							id: 1,
							goodsCategoryName: '果茶',
							name: '霸气橙汁',
							displayOrder: 1,
							defaultPrice: 1050,
							isSell: true,
							image: 'https://img-shop.qmimg.cn/s23107/2020/04/27/4ebdb582a5185358c4.jpg?imageView2/2/w/600/h/600',
							description: '优选进口新奇士橙，搭配严选茉莉毛尖茶底，橙意满满。',
							number: null,
							realPrice: 1050,
							propertyStr: null,
							goodsPropertyVos: [
								{
									category: '温度',
									propertyList: [
										{
											id: 4,
											goodsId: 1,
											isDefault: false,
											category: '温度',
											propertyOption: '加冰',
											realPrice: null
										},
										{
											id: 5,
											goodsId: 1,
											isDefault: true,
											category: '温度',
											propertyOption: '常温',
											realPrice: null
										},
										{
											id: 6,
											goodsId: 1,
											isDefault: false,
											category: '温度',
											propertyOption: '加热',
											realPrice: null
										}
									]
								},
								{
									category: '大小',
									propertyList: [
										{
											id: 1,
											goodsId: 1,
											isDefault: false,
											category: '大小',
											propertyOption: '大杯',
											realPrice: 1600
										},
										{
											id: 2,
											goodsId: 1,
											isDefault: true,
											category: '大小',
											propertyOption: '中杯',
											realPrice: 1200
										},
										{
											id: 3,
											goodsId: 1,
											isDefault: false,
											category: '大小',
											propertyOption: '小杯',
											realPrice: 1000
										}
									]
								},
								{
									category: '甜度',
									propertyList: [
										{
											id: 7,
											goodsId: 1,
											isDefault: false,
											category: '甜度',
											propertyOption: '少量糖',
											realPrice: null
										},
										{
											id: 8,
											goodsId: 1,
											isDefault: true,
											category: '甜度',
											propertyOption: '标准糖',
											realPrice: null
										},
										{
											id: 9,
											goodsId: 1,
											isDefault: false,
											category: '甜度',
											propertyOption: '加糖',
											realPrice: null
										}
									]
								}
							]
						}
					]
				},
				{
					displayOrder: 5,
					goodsCategoryName: '甜点',
					goodsCategoryShow: true,
					goodsList: []
				},
				{
					displayOrder: 6,
					goodsCategoryName: '小吃',
					goodsCategoryShow: true,
					goodsList: [
						{
							id: 2,
							goodsCategoryName: '小吃',
							name: '香辣鸡腿',
							displayOrder: 0,
							defaultPrice: 450,
							isSell: true,
							image: null,
							description: '炸鸡腿',
							number: null,
							realPrice: 450,
							propertyStr: null,
							goodsPropertyVos: []
						}
					]
				}
			],
			// 商品最上方的轮放图
			swiperImages: [
				'https://img-shop.qmimg.cn/s23107/2020/04/27/4ebdb582a5185358c4.jpg?imageView2/2/w/600/h/600',
				'https://img-shop.qmimg.cn/s23107/2020/04/10/add546c1b1561f880d.jpg?imageView2/2/w/600/h/600'
			],
			currentCategoryName: '', // 默认分类
			categoryScrollTop: 0,
			menuScrollIntoView: '',
			cart: [], // 购物车
			goodDetailModalVisible: false, //是否饮品详情模态框
			currentGoods: {}, // 当前饮品
			selectedPropertyList: [], // 当前商品的属性
			cartPopupVisible: false,
			sizeCalcState: false,
			// 商品图片的基础路径
			goodsImageBaseUrl: this.$config.env != 'dev'
			  ? 'https://yuqy.club:9001/static/image/' : 'http://localhost:9002/static/image/'
		};
	},
	async onLoad() {
		await this.init();
	},
	computed: {
		...mapState(['userInfo', 'address', 'appProperties', 'takeType']),
		// 计算单个饮品添加到购物车的数量
		goodsCartNum() {
			return id =>
				this.cart.reduce((acc, cur) => {
					if (cur.id === id) {
						return (acc += cur.number);
					}
					return acc;
				}, 0);
		},
		// 计算该类商品的购买总数
		menuCartNum() {
			return goodsCategoryName =>
				this.cart.reduce((acc, cur) => {
					if (cur.goodsCategoryName === goodsCategoryName) {
						return (acc += cur.number);
					}
					return acc;
				}, 0);
		},
		// 计算购物车总数
		getCartGoodsNumber() {
			return this.cart.reduce((acc, cur) => acc + cur.number, 0);
		},
		// 计算购物车总价,
		getCartGoodsPrice() {
			let totalPrice = 0;
			this.cart.forEach(goods => {
				totalPrice += goods.realPrice * goods.number;
			});
			if (this.$store.getters.getTakeType == '外卖配送') {
				totalPrice += this.appProperties.packingPrice + this.appProperties.sendingPrice;
			}
			return totalPrice;
		}, // 是否达到起送价
		disabledPay() {
			return this.$store.getters.getTakeType == '外卖配送' && this.getCartGoodsPrice < this.appProperties.seedingNeedLeastPrice ? true : false;
		}, // 差多少元起送
		spread() {
			if (this.$store.getters.getTakeType != '外卖配送') return;
			return this.appProperties.seedingNeedLeastPrice - this.getCartGoodsPrice;
		}
	},
	methods: {
		//页面初始化
		async init() {
			let that = this;
			that.$request('/api-app/goods/goodsMenu/list', 'get').then(result => {
				that.goods = result.data;
			});
		},
		// 选择到店自取的方式下单
		takein() {
			this.$store.commit('set_take_type', '到店自取');
		},
		// 选择外卖配送的方式下单
		takeout() {
			if (!this.userInfo) {
				uni.navigateTo({ url: '/pages/login/login' });
				return;
			}

			this.$store.commit('set_take_type', '外卖配送');
			uni.navigateTo({
				url: '/pages/address/address?is_choose=true'
			});
		},
		handleMenuTap(goodsCategoryName) {
			// 点击菜单项事件
			if (!this.sizeCalcState) {
				this.calcSize();
			}

			this.currentCategoryName = goodsCategoryName;
			this.$nextTick(() => (this.categoryScrollTop = this.goods.find(item => item.goodsCategoryName == goodsCategoryName).top));
		},
		handleGoodsScroll({ detail }) {
			//商品列表滚动事件
			if (!this.sizeCalcState) {
				this.calcSize();
			}
			const { scrollTop } = detail;
			let tabs = this.goods.filter(item => item.top <= scrollTop).reverse();
			if (tabs.length > 0) {
				this.currentCategoryName = tabs[0].goodsCategoryName;
			}
		},
		// 辅助函数，滚动时判断事件用
		calcSize() {
			let h = 10;
			let view = uni.createSelectorQuery().select('#ads');
			view.fields(
				{
					size: true
				},
				data => {
					h += Math.floor(data.height);
				}
			).exec();

			this.goods.forEach(item => {
				let view = uni.createSelectorQuery().select(`#category-${item.goodsCategoryName}`);
				view.fields(
					{
						size: true
					},
					data => {
						item.top = h;
						h += data.height;
						item.bottom = h;
					}
				).exec();
			});
			this.sizeCalcState = true;
		},
		// 获取商品具体价格，如大杯商品，小杯商品价格不同
		getGoodsRealPrice(goods) {
			let realPrice = goods.realPrice;
			if (goods.goodsPropertyVos && goods.goodsPropertyVos.length) {
				let vos = goods.goodsPropertyVos;
				for (let i = 0; i < vos.length; i++) {
					let propertyList = vos[i].propertyList;
					for (let j = 0; j < propertyList.length; j++) {
						if (propertyList[j].isDefault && propertyList[j].realPrice) {
							realPrice = propertyList[j].realPrice;
							break;
						}
					}
				}
			}
			return realPrice;
		},
		// 显示当前商品的详情信息
		showGoodDetailModal(currentGoods) {
			currentGoods.number = 1;
			currentGoods.realPrice = this.getGoodsRealPrice(currentGoods);
			currentGoods.propertyStr = this.getGoodSelectedProps(currentGoods);
			this.currentGoods = JSON.parse(JSON.stringify(currentGoods)); // 深拷贝

			this.goodDetailModalVisible = true;
			this.selectedPropertyList = [];
			console.log('显示当前商品的详情信息', this.currentGoods);
		},
		closeGoodDetailModal() {
			// 关闭饮品详情模态框
			this.goodDetailModalVisible = false;
		},
		// 改变商品的某个默认属性值
		changePropertyDefault(categoryIndex, propetyIndex) {
			this.currentGoods.goodsPropertyVos[categoryIndex].propertyList.forEach(property => (property.isDefault = 0));
			this.currentGoods.goodsPropertyVos[categoryIndex].propertyList[propetyIndex].isDefault = 1;
			let realPrice = this.currentGoods.goodsPropertyVos[categoryIndex].propertyList[propetyIndex].realPrice;
			if (realPrice) this.currentGoods.realPrice = realPrice;
			this.currentGoods.number = 1;
			this.currentGoods.propertyStr = this.getGoodSelectedProps(this.currentGoods);
		},
		// 计算当前饮品所选属性，空格隔开
		getGoodSelectedProps(goods) {
			if (goods.goodsPropertyVos) {
				let propertyStr = '';
				goods.goodsPropertyVos.forEach(goodsPropertyVo => {
					goodsPropertyVo.propertyList.forEach(property => {
						if (property.isDefault) {
							propertyStr += property.propertyOption + ' ';
						}
					});
				});
				return propertyStr;
			}
			return '';
		},
		// 改变当前商品数量
		changeCurrentGoodsNumber(number) {
			this.currentGoods.number += number;
			if (this.currentGoods.number < 0) {
				this.currentGoods.number = 0;
			} else if (this.currentGoods.number >= 100) {
				this.currentGoods.number = 100;
			}
		},
		// 将当前商品加入到购物车
		addCurrentGoodsToCart() {
			if (this.currentGoods && this.currentGoods.number) {
				this.handleAddToCart(this.currentGoods);
			}
			this.closeGoodDetailModal();
		},
		// 减少购物车里的商品数量, goodsId和propertyStr去比较
		handleReduceFromCart(goods) {
			let propertyStr = this.getGoodSelectedProps(goods);
			let cart = this.cart;
			for (let i = cart.length - 1; i >= 0; i--) {
				if (cart[i].id == goods.id && cart[i].propertyStr == propertyStr) {
					if (cart[i].number <= 1) cart.splice(i, 1);
					else cart[i].number -= 1;
					return;
				}
			}
		},
		// 添加到购物车
		handleAddToCart(goods) {
			let propertyStr = this.getGoodSelectedProps(goods);
			goods.propertyStr = propertyStr;
			let cart = this.cart;
			for (let i = cart.length - 1; i >= 0; i--) {
				if (cart[i].id == goods.id && cart[i].propertyStr == propertyStr) {
					cart[i].number++;
					return;
				}
			}

			// 购物车里不存在
			if (!goods.number) goods.number = 1;
			this.cart.push(JSON.parse(JSON.stringify(goods)));
		},
		//打开/关闭购物车列表popup
		openCartPopup() {
			this.cartPopupVisible = !this.cartPopupVisible;
		},
		// 清空购物车
		handleCartClear() {
			uni.showModal({
				title: '提示',
				content: '确定清空购物车么',
				success: ({ confirm }) => {
					if (confirm) {
						this.cartPopupVisible = false;
						this.cart = [];
					}
				}
			});
		},
		// 在购物车里操作商品数量
		handleCartItemAdd(index) {
			this.cart[index].number += 1;
		},
		handleCartItemReduce(index) {
			if (this.cart[index].number === 1) {
				this.cart.splice(index, 1);
			} else {
				this.cart[index].number -= 1;
			}
			if (!this.cart.length) {
				this.cartPopupVisible = false;
			}
		},
		toPay() {
			console.log('进入支付页面');
			if (!this.userInfo) {
				uni.navigateTo({ url: '/pages/login/login' });
				return;
			}

			uni.setStorageSync('cart', JSON.parse(JSON.stringify(this.cart)));
			uni.navigateTo({
				url: '/pages/pay/pay'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
@import '~@/pages/menu/menu.scss';
</style>
